<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- <el-input v-model="listQuery.title" placeholder="用户名" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" /> -->

      <!-- <el-select v-model="listQuery.level" placeholder="代理级别"  style="width: 110px" class="filter-item">
        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />
      </el-select> -->
      <!-- <el-select v-model="listQuery.type" placeholder="Type" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select> -->
      <!-- <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        创建用户
      </el-button> -->
      <!-- <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        Export
      </el-button>
      <-->
      <!-- <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        代理线
      </el-checkbox> -->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="用户名" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
          <!-- <span class="link-type" @click="handleUpdate(row)">{{ row.title }}</span>
          <el-tag>{{ row.type | typeFilter }}</el-tag> -->
        </template>
      </el-table-column>
      <el-table-column label="操作时间" prop="timestamp" sortable="custom" width="170px" align="center" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" prop="timestamp" sortable="custom" width="150px" align="center" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.type }}</span>
        </template>
      </el-table-column>
      <el-table-column label="变更前" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ (row.old-0).toFixed(4) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="变更积分" width="180px" align="center">
        <template slot-scope="{row}">
          <span>{{ (row.changestr-0).toFixed(4) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="变更后" width="200px">
        <template slot-scope="{row}">
          <span>{{ (row.sumnum-0).toFixed(4) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="加速详情" width="340px">
        <template slot-scope="{row}">
          <!-- <span>{{ row.ranliao }}</span> -->
          <div v-if="row.text&&row.text.length" class="">
            <p v-for="el in row.text"> {{ el.name }} --- {{ el.acc }} <span v-if="el.day">---{{ el.day }}</span> </p>
          </div>
          <div v-else class="">
            -
          </div>

        </template>
      </el-table-column>
      <!-- <el-table-column label="总积分" width="340px">
        <template slot-scope="{row}">
          <p></p>
          <span>{{ row.banlace }}</span>
        </template>
      </el-table-column> -->
      <!-- v-if="showReviewer" -->
      <!-- <el-table-column  label="上级ID" min-width="90px" align="center">
        <template slot-scope="{row}">
          <span style="color:red;">{{ row.parentId || '-'}}</span>
        </template>
      </el-table-column>
      <el-table-column  label="代理级别" min-width="90px" align="center">
        <template slot-scope="{row}">
          <span style="color:red;">{{ row.level }}</span>
        </template>
      </el-table-column>
      <el-table-column  label="推广码" min-width="90px" align="center">
        <template slot-scope="{row}">
          <span style="color:red;">{{ row.rgcode }}</span>
        </template>
      </el-table-column> -->

    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

  </div>
</template>

<script>
const __ = {
  formatDate: (date, fmt) => {
    const padLeftZero = (str) => {
      return ('00' + str).substr(str.length)
    }
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    const o = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'h+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds()
    }
    for (const k in o) {
      if (new RegExp(`(${k})`).test(fmt)) {
        const str = o[k] + ''
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
      }
    }
    return fmt
  }
}
import { fetchUserListdetail, fetchPv, resetpwdfn, createArticle, createuser, updateArticle } from '@/api/article'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    formatDate(time) {
      console.log(time)
      return __.formatDate(new Date(time), 'yyyy-MM-dd hh:mm:ss').split(' ')[0]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      resetpwd: false,
      listQuery: {
        page: 1,
        limit: 20,
        sort: '+id'
      },
      importanceOptions: ['全部', '一级代理', '二级代理', '三级代理', '四级代理', '五级代理', '六级代理', '七级代理', '八级代理', '九级代理'],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        username: '',
        pwd: '',
        rgcode: ''
      },
      dialogFormVisible: false,
      dialogFormVisible2: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        username: [{ required: true, message: '用户名为必填项', trigger: 'blur' }],
        pwd: [{ required: true, message: '密码为必填项', trigger: 'blur' }]
        // type: [{ required: true, message: 'type is required', trigger: 'change' }],
        // timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        // title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
    console.log(this.$route)
  },
  methods: {
    getList() {
      this.listLoading = true
      // {name: this.$route.params.name}
      this.listQuery['name'] = this.$route.params.name
      fetchUserListdetail(this.listQuery).then(response => {
        const arr = [];
        arr.push(response)
        // arr.forEach(item => {
        //   if (item.text) item.text = JSON.parse(item.text)
        // })
        // console.log(arr)
        this.list =  arr;
        // console.log(this.list ,'============',response)
        // this.total = response.total
        this.listLoading = false
        // Just to simulate the time of the request
        // setTimeout(() => {
        //   this.listLoading = false
        // }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    handleCreate() {
      // this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          // this.temp.author = 'vue-element-admin'
          createuser(this.temp).then((res) => {
            // this.list.unshift(this.temp)
            console.log(res)
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    resetpwdsub() {
      if (!this.temp.pwd) {
        return this.$message({
          message: '请填写重置密码！',
          type: 'error'
        })
      }
      resetpwdfn({
        name: this.temp.name,
        pwd: this.temp.pwd
      }).then(res => {
        if (res.code == 0) {
          this.$message({
            message: '用户：' + this.temp.name + '，密码已重置！',
            type: 'success'
          })
          this.temp = {}
          this.resetpwd = false
        }
        console.log(res)
      })
      console.log(this.temp)
    },
    handleUpdate(row) {
      this.resetpwd = true
      this.temp = row
      console.log(row)
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateArticle(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      console.log(row, index)
      this.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(1);
      }).catch(() => {});

      return false;
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }

  }
}
</script>
